package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Finance;
import cn.itcast.domain.cargo.Invoice;
import cn.itcast.service.cargo.FinanceService;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.web.controller.BaseController;


import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;



@Controller
@RequestMapping("/cargo/finance/")
public class FinanceController extends BaseController {
    @Reference
    private FinanceService financeService;

    @Reference
    private InvoiceService invoiceService;


    //展示报运单列表
    @RequestMapping("/list")
    public String financeList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize){
        PageInfo<Finance> pageInfo= financeService.findAll(getLoginCompanyId(),pageNum,pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/finance/finance-list";
    }



    //去新建列表
    @RequestMapping("/toAdd")
    public String toAdd(String invoiceId){
         //展示数据，通过id查找发票
        Invoice invoice = invoiceService.findById(invoiceId);
        request.setAttribute("invoice",invoice);
         return "cargo/finance/finance-add";
    }

    //增加财务保运表
    @RequestMapping("/edit")
    public String add(Invoice invoice, Date inputDate){
        //单独获取下制表时间Invoice invoice
        //更改发票状态
        Invoice invoiceUpdate = new Invoice();
        invoiceUpdate.setStatus(1);
        invoiceService.update(invoiceUpdate);

        String scNo= invoice.getScNo();
       String []  arr= scNo.split("\\s+");
       for(String  no: arr){
            //封装财务报运单
            Finance finance = new Finance();
            finance.setInvoiceId(invoice.getInvoiceId());
            finance.setInvoiceMoney(invoice.getInvoiceMoney().longValue());
            finance.setInvoiceTime(invoice.getInvoiceTime());
            finance.setExportNos(invoice.getScNo());
            finance.setShipmentPort(invoice.getShipmentPort());
            finance.setDestinationPort(invoice.getDestinationPort());
            finance.setConsignee(invoice.getConsignee());
            finance.setCompanyId(getLoginCompanyId());
            finance.setInvoiceTime(inputDate);
            financeService.addFinance(finance);
       }
        //循环增加财务报运单invoice finance,

       return "redirect:/cargo/finance/list.do";
    }

    //查看财务保运单
    @RequestMapping("/toView")
    public String toView(String financeId){
        Finance finance = financeService.findBySOId(financeId);
        request.setAttribute("finance",finance);
        return "cargo/finance/finance-view";
    }


   //以PDF的方式下载委托单
    @RequestMapping("/printPdf")
    @ResponseBody
    public void exportPdf() throws JRException, IOException {
        //1、得到Jasper文件的输入流
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/finance.jasper");

        //2、把模板与数据结合，得到JasperPrint对象（数据+模板结合）
        //封装委托表的数据
        List<Finance> financeList = financeService.findFinance(getLoginCompanyId());
        //把list集合的数据交给数据源
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(financeList);
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, new HashMap<>(),dataSource);

        //4、设置响应头，下载
        response.setHeader("content-disposition","attachment;filename=Finance.pdf");
        //3、把PDF文件输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }
   //下载出货表
   @RequestMapping("/printExcel.do")
   @ResponseBody
   public void printExcel() throws IOException {

        //导出Excel，不使用模板
        //按照出货表要求获取对应的数据
        List<Finance> FinanceList = financeService.findFinance(getLoginCompanyId());
        //创建工作薄
        Workbook workbook = new XSSFWorkbook();
        //创建工作单
        Sheet sheet = workbook.createSheet("报运表");
        //制作出货表
        //设置表格基本大小
        //1、合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 7));
        //2、设置列宽
        sheet.setColumnWidth(0, 6 * 256);
        sheet.setColumnWidth(1, 21 * 256);
        sheet.setColumnWidth(2, 16 * 256);
        sheet.setColumnWidth(3, 16 * 256);
        sheet.setColumnWidth(4, 11 * 256);
        sheet.setColumnWidth(5, 11 * 256);
        sheet.setColumnWidth(6, 11 * 256);
        sheet.setColumnWidth(7, 11 * 256);
        sheet.setColumnWidth(8, 11 * 256);
        //3,创建第一行
        Row row = sheet.createRow(0);
        String title = "财务报运表";
        //创建单元格
        Cell cell = row.createCell(1);
        cell.setCellStyle(bigTitle(workbook));
        cell.setCellValue(title);

        //创建第二行
        row=sheet.createRow(1);
        String[] titles={"财务单号","制表时间","发票报运单","金额","装运港","目的港","收货人"};
        for (int i = 0; i <titles.length ; i++) {
             cell = row.createCell(i+1);
             cell.setCellStyle(title(workbook));
             cell.setCellValue(titles[i]);
        }
        //将查询出的数据遍历设置到Excel中
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        int index=2;
        for (Finance finance : FinanceList) {
            row=sheet.createRow(index++);

            //逐个封装数据进表格
            //财务单号
            String  financeId= finance.getFinanceId();
            if(financeId!=null){
                cell= row.createCell(1);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(financeId);
            }

            //制表时间
         Date inputDate= finance.getInputDate();
            if(inputDate!=null){
                cell = row.createCell(2);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(simpleDateFormat.format(inputDate));
            }

            //发票报运单
            String  invoiceId= finance.getInvoiceId();
            if(invoiceId!=null){
                cell = row.createCell(3);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(invoiceId);
            }


            //金额
             Long invoiceMoney= finance.getInvoiceMoney();
            if(invoiceMoney!=null){
                cell = row.createCell(4);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(invoiceMoney);
            }


            //装运港
            String  shipmentPort= finance.getShipmentPort();
            if(shipmentPort!=null){
                cell = row.createCell(5);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(shipmentPort);
            }

            //目的港
            String  destinationPort= finance.getDestinationPort();
            if(destinationPort!=null){
                cell = row.createCell(6);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(destinationPort);
            }

            //收货人
             String  consignee= finance.getConsignee();
            if(consignee!=null){
                cell = row.createCell(7);
                //设置样式
                cell.setCellStyle(text(workbook));
                //设置内容
                cell.setCellValue(consignee);
            }

        }
       String fileName="财务报运.xlsx";
       fileName= URLEncoder.encode(fileName,"utf-8");
       response.setHeader("content-disposition","attachment;filename="+fileName);
       workbook.write(response.getOutputStream());
   }
    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }

}
